<template>
  <div v-loading="loading">
    <div class="mg-b-8">
      <px-button type="primary" :icon="ArrowLeft" @click="goBack">返回</px-button>
    </div>
    <px-descriptions title="节能决策信息" :column="3" border class="info-content">
      <px-descriptions-item label="节能事项名称"> {{ analysisData.name }} </px-descriptions-item>
      <px-descriptions-item label="节约能源"> {{ energyMap[analysisData.kind] }} </px-descriptions-item>
      <px-descriptions-item label="执行时间"> {{ analysisData.startTime }} - {{ analysisData.endTime }} </px-descriptions-item>
      <px-descriptions-item label="执行人"> {{ analysisData.executor }} </px-descriptions-item>
      <px-descriptions-item label="负责人"> {{ analysisData.owner }} </px-descriptions-item>
      <px-descriptions-item label="节能描述"> {{ analysisData.description }} </px-descriptions-item>
    </px-descriptions>
    <div class="title">节能效果</div>
    <div class="result-info">
      <div class="info-column first-column">
        <div class="cell" />
        <div class="cell">节能前</div>
        <div class="cell">节能后</div>
      </div>
      <div class="info-column">
        <div class="cell">月度平均能耗（{{ energyUnit[analysisData.kind] }}）</div>
        <div class="cell content-cell">{{ analysisData.avgBefore }}</div>
        <div class="cell content-cell">
          <span>{{ analysisData.avgAfter }}</span>
          <span style="margin-left: 8px">
            <px-icon v-if="analysisData.avgRatio && getYearOnYear(analysisData.avgAfter, analysisData.avgBefore) < 0" color="#10B981"
              ><Bottom
            /></px-icon>
            <px-icon v-if="analysisData.avgRatio && getYearOnYear(analysisData.avgAfter, analysisData.avgBefore) > 0" color="#EF4444"
              ><Top
            /></px-icon>
            {{ getYearOnYear(analysisData.avgAfter, analysisData.avgBefore) + "%" }}
          </span>
        </div>
      </div>
      <div class="info-column">
        <div class="cell">月度最大能耗（{{ energyUnit[analysisData.kind] }}）</div>
        <div class="cell content-cell">
          <span>{{ formatYearMonth(analysisData.maxBeforeDate) }}</span>
          <span style="margin-left: 16px">{{ analysisData.maxBefore }}</span>
        </div>
        <div class="cell content-cell">
          <span>{{ formatYearMonth(analysisData.maxAfterDate) }}</span>
          <span style="margin-left: 16px">{{ analysisData.maxAfter }}</span>
          <span style="margin-left: 16px">
            <px-icon v-if="analysisData.maxRatio && getYearOnYear(analysisData.maxAfter, analysisData.maxBefore) < 0" color="#10B981"
              ><Bottom
            /></px-icon>
            <px-icon v-if="analysisData.maxRatio && getYearOnYear(analysisData.maxAfter, analysisData.maxBefore) > 0" color="#EF4444"
              ><Top
            /></px-icon>
            {{ getYearOnYear(analysisData.maxAfter, analysisData.maxBefore) + "%" }}
          </span>
        </div>
      </div>
      <div class="info-column">
        <div class="cell">月度最小能耗（{{ energyUnit[analysisData.kind] }}）</div>
        <div class="cell content-cell">
          <span>{{ formatYearMonth(analysisData.minBeforeDate) }}</span>
          <span style="margin-left: 16px">{{ analysisData.minBefore }}</span>
        </div>
        <div class="cell content-cell">
          <span>{{ formatYearMonth(analysisData.minAfterDate) }}</span>
          <span style="margin-left: 16px">{{ analysisData.minAfter }}</span>
          <span style="margin-left: 16px">
            <px-icon v-if="analysisData.minRatio && getYearOnYear(analysisData.minAfter, analysisData.minBefore) < 0" color="#10B981"
              ><Bottom
            /></px-icon>
            <px-icon v-if="analysisData.minRatio && getYearOnYear(analysisData.minAfter, analysisData.minBefore) > 0" color="#EF4444"
              ><Top
            /></px-icon>
            {{ getYearOnYear(analysisData.minAfter, analysisData.minBefore) + "%" }}
          </span>
        </div>
      </div>
    </div>
    <div ref="chartRef" class="chart" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import * as echarts from "echarts";
import { ArrowLeft } from "@px-ui/icons-vue";
import { analysisAPI } from "@/api/energy/savingAnalysis";

const props = defineProps({
  rowData: {
    type: Object,
    default: () => {}
  },
  energyMap: {
    type: Object,
    default: () => {}
  }
});

const emits = defineEmits(["goBack"]);

const chartRef = ref(null);

const loading = ref(false);
const analysisData = ref({});

const energyUnit = ref({
  electricity: "kwh",
  running: "m³",
  reclaim: "m³",
  ng: "Nm³",
  steam: "t",
  hot: "t",
  cda: "Nm³",
  n2: "Nm³",
  h2: "Nm³",
  o2: "Nm³",
  ar: "Nm³",
  he: "Nm³",
  co2: "Nm³",
  diesel: "t"
});

onMounted(() => {
  getAnalysisData();
});

const goBack = () => {
  emits("goBack");
};

const getAnalysisData = async () => {
  try {
    loading.value = true;
    const res = await analysisAPI({ id: props.rowData.id });
    analysisData.value = res;
    nextTick(() => {
      drawChart();
    });
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

const getYearOnYear = (value, lastYearValue) => {
  if (value === null || value === undefined || lastYearValue === null || lastYearValue === undefined || lastYearValue === 0) {
    return "--";
  }
  return (((value - lastYearValue) / lastYearValue) * 100).toFixed(2);
};

const formatYearMonth = data => {
  if (data === null || data === "" || data === undefined) {
    return "--";
  } else {
    return `${data.toString().substring(0, 4)}年${data.toString().slice(-2)}月`;
  }
};

const drawChart = () => {
  let myChart = echarts.init(chartRef.value);
  let xData = analysisData.value?.bar?.xaxis;
  let lineData = analysisData.value?.startTime ? `${analysisData.value?.startTime.split("-")[0]}-${analysisData.value?.startTime.split("-")[1]}` : "";
  if (!xData.includes(lineData)) {
    xData.push(lineData);
  }
  let option = {
    toolbox: {
      feature: {
        saveAsImage: { show: true }
      }
    },
    legend: {
      data: ["去年同期", "当年"]
    },
    tooltip: {
      show: true
    },
    xAxis: [
      {
        type: "category",
        data: xData,
        axisPointer: {
          type: "shadow"
        }
      }
    ],
    yAxis: {
      name: `单位（${energyUnit.value[analysisData.value.kind]}）`,
      type: "log",
      base: 10,
      min: 1,
      splitLine: {
        show: true,
        axisLine: {
          show: true
        }
      },
      axisLabel: {
        formatter: function (value) {
          if (value === 0) {
            return value;
          }
          const absValue = Math.abs(value);

          // 极大数值使用科学计数法
          if (absValue >= 1e15) {
            return value.toExponential(2);
          }
          const units = ["", "K", "M", "B", "T"];
          const order = Math.min(Math.floor(Math.log10(absValue) / 3), units.length - 1);
          const unitValue = absValue / Math.pow(10, order * 3);
          return (value < 0 ? "-" : "") + unitValue.toFixed(2) + units[order];
        }
      }
    },
    series: [
      {
        name: "去年同期",
        type: "bar",
        markLine: {
          symbolSize: [8, 8],
          label: {
            show: true,
            padding: [0, 0, 5, 0],
            formatter() {
              return "执行开始时间";
            }
          },
          data: [
            {
              xAxis: lineData
            }
          ],
          lineStyle: {
            width: 1,
            color: "#979797"
          }
        },
        data: analysisData.value?.bar?.yaxis.filter(item => item?.name?.includes("去年"))[0]?.value
      },
      {
        name: "当年",
        type: "bar",
        data: analysisData.value?.bar?.yaxis.filter(item => item?.name?.includes("当年"))[0]?.value
      }
    ]
  };
  myChart.clear();
  option && myChart.setOption(option);
  myChart.resize();
};
</script>

<style lang="scss" scoped>
:deep(.px-descriptions__label) {
  width: 120px;
}

.mg-b-8 {
  margin-bottom: 8px;
}

.title {
  margin: 16px 0;
  font-size: 16px;
  font-weight: 700;
}

.result-info {
  display: flex;
  align-items: center;

  .info-column {
    width: 400px;

    .cell {
      width: 100%;
      height: 46px;
      line-height: 46px;
      text-align: left;
    }
  }

  .first-column {
    width: 100px;
    font-weight: 500;
  }
}

.chart {
  width: 100%;
  height: calc(100vh - 530px);
}
</style>
